<template>
  <view class="page">
    <view v-if="$data.info">
      <view class="top">
        <view class="basic">
          <view class="basic_img">
            <image :src="$data.info._picurl" />
          </view>
          <view class="basic_content">
            <view class="basic_content--title">
              {{ $data.info.serviceTitle }}
            </view>
            <view class="basic_content--price text-price">
              {{ $data.info.firstTotalPrice }}
            </view>
          </view>
        </view>
      </view>
      <!-- 申请金额 -->
      <view class="price margin-top padding bg-white">
        <view class="price_title">申请金额</view>
        <view class="text-price price_price">
          {{ $data.orderRefundPrice }}
        </view>
      </view>
      <!-- 申请原因 -->
      <view
        class="reason margin-top padding bg-white"
        @tap="() => ($data.reasonShow = true)"
      >
        <view class="reason_title">申请原因</view>
        <view class="flex align-center">
          <view
            v-if="$data.reasonName"
            class="reason_name u-line-1 margin-right-xs"
          >
            {{ $data.reasonName }}
          </view>
          <up-icon name="arrow-right" color="#111111"></up-icon>
        </view>
      </view>
      <!-- 申请说明 -->
      <view class="price margin-top padding bg-white">
        <view class="price_title">申请说明</view>
        <view class="price_price">
          <up-textarea
            v-model="$data.remark"
            placeholder="如有其他要求请备注"
            count
            :height="130"
            :maxlength="200"
          ></up-textarea>
        </view>
        <!-- <view class="price_title margin-tb">上传图片(最多上传8张图片)</view> -->
        <!-- <up-upload
          :fileList="$data.fileList"
          :previewFullImage="true"
          :deletable="true"
          @afterRead="juAfterRead($event, 'fileList')"
          @delete="juDeletePic($event, 'fileList')"
          name="eventImages"
          multiple
          width="24vw"
          height="24vw"
          :maxCount="8"
          @oversize="oversize"
          accept="image"
          :maxSize="uploadSize"
        >
          <view class="upload-custom">
            <image :src="ImgIconPhotoGray" mode="scaleToFill" />
          </view>
        </up-upload> -->
      </view>
      <!-- 联系电话 -->
      <view class="price margin-top padding bg-white flex align-center">
        <view class="price_title text-nowarp">联系电话</view>
        <view class="margin-left">
          <input
            v-model="$data.phone"
            type="number"
            placeholder="请输入联系电话"
          />
        </view>
      </view>
      <!-- $data.douyinOrderId:{{ $data.douyinOrderId }} $data.douyinPrice:{{
        $data.douyinPrice
      }}
      $data.orderServiceId:{{ $data.orderServiceId }} -->
      <!-- 底部按钮 -->
      <view class="foot foot_box">
        <view class="btn btn_save" @tap="onSave">提交申请</view>
        <!-- @refund="onRefund" -->
        <!-- @applyrefund="applyRefund" -->
        <!-- <pay-button
          :mode="1"
          :order-status="1"
          :order-id="$data.douyinOrderId"
          :refund-total-amount="$data.douyinPrice"
          @refund="onRefund"
          @applyrefund="applyRefund"
          @error="onError"
        /> -->
      </view>
    </view>
    <PopupReason
      v-model:show="$data.reasonShow"
      @confirm="(e) => ($data.reasonName = e)"
    />
    <PopupLogin />
  </view>
</template>

<script setup>
// firstStatus=2 或者3 才能进这个页
import { getCurrentInstance, reactive, ref, nextTick, computed } from "vue";
import { onLoad, onShow, onHide, onReady, onUnload } from "@dcloudio/uni-app";
import {
  cancelSubscribeOrder,
  getOrderDetail,
  refundOrder,
  refundOrderDetail,
} from "../../../../api/Interface/order";
import errorCode from "../../../../utils/http/errorCode";
import BasicConfig from "../../../../utils/config";
import {
  orderRefundStatus,
  orderStatus,
  orderStatusConfig,
} from "../../../../enums/order";
import { jumpPage } from "../../../../utils/route/route";
import { oversize, uploadSize } from "../../../../utils/utils";
import { ImgIconPhotoGray } from "../../../../utils/iconMap";
import { useAfterRead, useDeletePic } from "../../../../hooks/useUpload";
import PopupReason from "../components/PopupReason.vue";
import { useImgSrc } from "../../../../hooks/useImg";
import { useSubscribeTemplate } from "../../../../hooks/useSubscribe";
import { subscribeEnum } from "../../../../enums/subscribe";
import { isDev } from "../../../../utils/env";
import { useTTPlugin } from "../../../../hooks/useTT";
import { goodsType, reservaSwitch } from "../../../../enums/goods";
const $data = reactive({
  localNo: "",
  orderServiceId: "",
  info: {},
  reasonShow: false,
  remark: "",
  fileList: [],
  phone: "",
  reasonName: "", // 申请原因value
  orderRefundPrice: 0, // 退款金额
  douYinPayJson: null, // 抖音退款
  douyinOrderId: "", // 抖音订单id
  douyinPrice: 0, // 抖音订单价格
  loading: false, // 提交中
  workSecondPrice: 0,
  refundInfo: null,
});
const init = () => {
  // if (isDev) {
  //   $data.phone = "";
  // }
  refundOrderDetail({
    localNo: $data.localNo,
    orderServiceId: $data.orderServiceId,
  }).then((res) => {
    console.log("退款订单详情", res.data);
    if (res.code === errorCode.success) {
      $data.refundInfo = res.data;
      $data.orderRefundPrice = res.data.orderRefundPrice;
      $data.douYinPayJson = res.data.douYinPayJson;
      $data.workSecondPrice = res.data.workSecondPrice;
      if ($data.douYinPayJson) {
        // if ($data.douYinPayJson.sku_list) {
        //   $data.douYinPayJson.sku_list.forEach((sku) => {
        //     sku.skuId = sku.sku_id;
        //     sku.skuType = sku.sku_id_type;
        //   });
        //   $data.douYinPayJson.skuList = $data.douYinPayJson.sku_list;
        // }
        if ($data.douYinPayJson.item_order_info_list) {
          $data.douYinPayJson.item_order_info_list.forEach((item) => {
            item.itemOrderId = item.item_order_id;
            // item.refundAmount = item.price;
          });
        }
        $data.douyinOrderId = $data.douYinPayJson.order_id;
        $data.douyinPrice = $data.douYinPayJson.total_amount;
      }
      $data.remark = res.data.reasonContent;
    }
  });
  getOrderDetail({
    localNo: $data.localNo,
    orderServiceId: $data.orderServiceId,
  }).then((res) => {
    if (res.code === errorCode.success) {
      $data.info = res.data;
      if ($data.info) {
        setTitle();
        $data.info._picurl = useImgSrc($data.info.picurl);
      }
    }
  });
};
const setTitle = () => {
  // uni.setNavigationBarTitle({
  //   title: orderStatusConfig[$data.info.firstStatus]?.label ?? "",
  // });
};
const onRefund = (e) => {
  // TODO: 需要真机调试
  console.log("onRefund", e);
  const { status, result } = e.detail;
  if (status === "success") {
    const { refundId, outRefundNo } = result;
  } else {
    const { errMsg } = result;
  }
};
const applyRefund = (e) => {
  console.log("canIUse", tt.canIUse("industrySDK.pay-button"));
  // 判断是否支持行业sdk 的 pay-button 组件
  if (tt.canIUse("industrySDK.pay-button")) {
    // do something
  }
  console.log("applyRefund", e);
  const { orderId } = e.detail;
  const extra = { orderId }; // 开发者需要透传的参数，可自定义内容
  return new Promise((resolve) => {
    resolve(extra);
  });
};
const onError = (e) => {
  console.log("onError", e);
};
const onSave = async () => {
  console.log("提交申请$data.loading前", $data.loading);
  if ($data.loading) {
    return;
  }
  console.log("提交申请$data.loading后", $data.loading);
  if (!$data.reasonName) {
    BasicConfig.toast("请选择申请原因");
    return;
  }
  if (!$data.remark) {
    BasicConfig.toast("请输入申请说明");
    return;
  }
  if (!uni.$u.test.mobile($data.phone)) {
    BasicConfig.toast("请输入正确的手机号");
    return;
  }
  $data.loading = true;
  let can = false;
  if (
    $data.info.goodsType == goodsType.group ||
    ($data.info.goodsType == goodsType.reservation &&
      $data.refundInfo?.refundStatus == orderRefundStatus.can &&
      !$data.refundInfo?.douYinBookId)
  ) {
    can = true;
  } else {
    can = await cancel();
  }
  console.log("can", can);
  if (!can) return;
  const refundInfo = {
    reason: [$data.reasonName],
  };
  const callbackData = {
    localNo: $data.localNo,
    reasonName: $data.reasonName,
    orderTotalPrice: $data.douYinPayJson.total_amount, // $data.info.firstTotalPrice,
    reasonContent: $data.remark,
    img: $data.fileList.map((m) => m.file.data[0].url).join(","),
    phone: $data.phone,
    workSecondPrice: $data.workSecondPrice,
  };
  console.log("refundInfo", refundInfo);
  console.log("callbackData", callbackData);
  // console.log("skuList", [$data.douYinPayJson]);
  console.log("$data.douYinPayJson", $data.douYinPayJson);
  console.log("itemOrderList", $data.douYinPayJson?.item_order_info_list);
  console.log("refundAmount", $data.douYinPayJson.total_amount);
  const NTT = useTTPlugin();
  NTT.applyRefund({
    outOrderNo: $data.localNo,
    refundInfo,
    // skuList: $data.douYinPayJson.skuList,
    itemOrderList: $data.douYinPayJson.item_order_info_list, // 全额退
    // itemOrderDetail: $data.douYinPayJson?.item_order_detail, // 部分退
    // refundAmount: $data.douYinPayJson.total_amount,
    // refund_amount: $data.douYinPayJson.total_amount,
    // refundTotalAmount: $data.douYinPayJson.total_amount,
    callbackData,
    success: (success) => {
      console.log("退款success", success);
      BasicConfig.toast("提交成功");
      setTimeout(() => {
        // uni.navigateBack({
        //   delta: 1,
        // });
        $data.loading = false;
        jumpPage({
          to: `/package-service/pages/order/afterSales/detail`,
          query: {
            localNo: $data.localNo,
          },
          mode: "reLaunch",
        });
      }, 1000);
    },
    fail: (fail) => {
      console.log("退款fail", fail);
      BasicConfig.toast("提交失败，请联系管理员！");
      $data.loading = false;
    },
  });
  // NTT.applyRefund({
  //   outOrderNo: $data.localNo,
  //   refundInfo,
  //   // skuList: $data.douYinPayJson.skuList,
  //   itemOrderList: $data.douYinPayJson?.item_order_info_list, // 全额退
  //   // 部分退 数据格式
  //   //    "item_order_detail": [
  //   //   {
  //   //     "item_order_id": "{{item_order_detail_0}}",//先买单的item，多券则多个
  //   //     "refund_amount": 100, // 原支付金额
  //   //     "deduct_fee_amount"：20 // 手续费
  //   //   },
  //   // ],
  //   itemOrderDetail: $data.douYinPayJson?.item_order_detail, // 部分退
  //   refundAmount: $data.douYinPayJson?.total_amount,
  //   // refundTotalAmount: $data.douYinPayJson.total_amount,
  //   callbackData,
  //   success: (success) => {
  //     console.log("退款success", success);
  //     BasicConfig.toast("提交成功");
  //     setTimeout(() => {
  //       // uni.navigateBack({
  //       //   delta: 1,
  //       // });
  //       $data.loading = false;
  //       jumpPage({
  //         to: `/package-service/pages/order/afterSales/detail`,
  //         query: {
  //           localNo: $data.localNo,
  //         },
  //         mode: "reLaunch",
  //       });
  //     }, 1000);
  //   },
  //   fail: (fail) => {
  //     console.log("退款fail", fail);
  //     BasicConfig.toast("提交失败，请联系管理员！");
  //     $data.loading = false;
  //   },
  // });
  // uni.showModal({
  //   content: "确认提交?",
  //   success: (success) => {
  //     if (success.confirm) {
  //       refundOrder({
  //         localNo: $data.localNo,
  //         reasonName: $data.reasonName,
  //         orderTotalPrice: $data.info.firstTotalPrice,
  //         reasonContent: $data.remark,
  //         img: $data.fileList.map((m) => m.file.data[0].url).join(","),
  //         phone: $data.phone,
  //       }).then(async (res) => {
  //         BasicConfig.toast(res.msg);
  //         if (res.code === errorCode.success) {
  //           const ids = [
  //             // subscribeEnum.service.refundApply,
  //             subscribeEnum.service.refundSuccess,
  //             subscribeEnum.service.refundFail,
  //           ];
  //           try {
  //             await useSubscribeTemplate(ids);
  //           } catch (e) {
  //             console.log("useSubscribeTemplate err", e);
  //           }
  //           setTimeout(() => {
  //             uni.navigateBack({
  //               delta: 1,
  //             });
  //           }, 1500);
  //         }
  //       });
  //     }
  //   },
  // });
};

const cancel = async () => {
  const { code, msg } = await cancelSubscribeOrder({
    localNo: $data.localNo,
  }).catch((err) => {
    return Promise.resolve(false);
  });
  if (code !== errorCode.success) {
    $data.loading = false;
    BasicConfig.toast(msg);
    return Promise.resolve(false);
  } else return Promise.resolve(true);
};
const previewImage = (url) => {
  uni.previewImage({
    urls: [fileUrl + url],
  });
};
// 删除图片
const juDeletePic = (event, key) => {
  $data[key] = useDeletePic(event, $data[key]);
  console.log("fileList del", $data[key]);
};
const juAfterRead = async (event, key) => {
  console.log("juAfterRead", event);
  const { data } = await useAfterRead({
    event,
    fileList: $data[key],
    formData: { user: "test" },
    key: "file",
  });
  if (data) {
    data.forEach((item) => {
      if (item.file) {
        item.url = item.file.url;
      }
    });
    $data[key] = data;
  }
  console.log("fileList", $data[key]);
};
onLoad((options) => {
  $data.loading = false;
  $data.localNo = options.localNo;
  $data.orderServiceId = options.orderServiceId;
  init();
});
onUnload(() => {});
onReady(() => {});
</script>

<style lang="scss" scoped>
@import "../../../static/style/order/detail/common.scss";
.page {
  color: #111111 !important;
  .basic {
    padding-bottom: 30rpx;
  }
  .price {
    color: #111111;
    &_title {
      font-size: 32rpx;
      // font-weight: 700;
    }
    &_price {
      font-size: 50rpx;
      // font-weight: 700;
      margin-top: 30rpx;
    }
  }
  .reason {
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #111111;
    &_title {
      font-size: 32rpx;
    }
    &_name {
      width: 400rpx;
    }
  }
  ::v-deep .u-textarea {
    border-radius: 20rpx;
  }
  .upload-custom {
    background: #f1f1f1;
    border: 1px dashed #aaaaaa;
    border-radius: 15rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 24vw;
    height: 24vw;
    image {
      width: 100%;
      height: 100%;
    }
  }
  ::v-deep .u-upload__wrap__preview {
    margin: 0 !important;
    margin-bottom: 30rpx !important;
    &:not(:nth-of-type(3n)) {
      margin-right: 30rpx !important;
    }
  }
}
</style>
